import * as React from 'react';
import { map, get, includes } from 'lodash';
import { Select, Form, Input, Button, Icon } from 'antd';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadableDragger = LoadableComponent(() => import('components/common/Dragger'));
const LoadableMedia = LoadableComponent(() => import('components/common/Media'));

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/preview';

const FormItem = Form.Item;

/**
 * 绘本抢先看表单
 */
interface EditFormProps {
  onSubmit: (data: Record<string, any>) => any;
  editPreview: any;
  availableLevels: object[];
  allLevels: object[];
  form: any;
  loadingGroup: any;
}
interface EditFormState {
  cover: any;
}

/**
 * Preview新增或修改
 */
class EditForm extends React.Component<EditFormProps, EditFormState> {
  static defaultProps: EditFormProps = {
    onSubmit: () => {},
    form: {},
    loadingGroup: {},
    editPreview: 0,
    allLevels: [],
    availableLevels: [],
  };
  constructor(props: EditFormProps) {
    super(props);

    this.state = {
      cover: get(props.editPreview, 'cover', null),
    };
  }

  handleSubmit = (e: any) => {
    e.preventDefault();
    this.props.form.validateFields((err: any, values: any) => {
      if (err) return;

      this.props.onSubmit(values);
    });
  };

  // cover
  renderCover(image: any) {
    const { form } = this.props;
    if (image) {
      return (
        <div style={{ position: 'relative' }}>
          <LoadableMedia
            imageStyle={{ width: 300 }}
            attachment={image}
            onDestroy={() => {
              this.setState(
                {
                  cover: null,
                },
                () => {
                  form.setFieldsValue({
                    cover: null,
                  });
                }
              );
            }}
          />
        </div>
      );
    }

    return (
      <LoadableDragger
        key="image"
        accept="image"
        selectMax={1}
        onDone={(response: any) => {
          const cover = response.files[0];
          this.setState(
            {
              cover,
            },
            () => {
              form.setFieldsValue({
                cover: cover.id,
              });
            }
          );
        }}>
        <Button type="primary">
          <Icon type="notification" />
        </Button>
      </LoadableDragger>
    );
  }

  render() {
    const { editPreview, loadingGroup, form, allLevels, availableLevels } = this.props;
    const { getFieldDecorator } = form;
    const { cover } = this.state;

    const availableCodes = map(availableLevels, (item: any) => {
      return item.code;
    });

    const loadingKey = editPreview ? ACTIONS.UPDATE : ACTIONS.CREATE;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };

    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem {...formItemLayout} label="名称">
          {getFieldDecorator('name', {
            rules: [
              {
                required: true,
                message: '名称是必填项',
              },
            ],
            initialValue: get(editPreview, 'name', '精彩绘本抢先看'),
          })(<Input placeholder="名称" />)}
        </FormItem>
        <FormItem {...formItemLayout} label="难度级别">
          {getFieldDecorator('level', {
            rules: [
              {
                required: true,
                message: '绘本抢先看难度级别是必填项',
              },
            ],
            initialValue: get(editPreview, 'level', null),
          })(
            <Select placeholder="请选择绘本难度级别" style={{ width: '100%' }}>
              {allLevels.map((item: any) => {
                return (
                  <Select.Option
                    disabled={!includes(availableCodes, item.code)}
                    key={item.code}
                    value={item.code}>
                    {item.desc}
                  </Select.Option>
                );
              })}
            </Select>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label="封面图片" style={{ verticalAlign: 'middle' }}>
          {getFieldDecorator('cover', {
            rules: [
              {
                required: true,
                message: '封面图片是必填项',
              },
            ],
            initialValue: get(cover, 'id', null),
          })(this.renderCover(cover))}
        </FormItem>

        <FormItem {...tailFormItemLayout}>
          <Button
            icon="save"
            type="primary"
            htmlType="submit"
            size="large"
            loading={isLoading(loadingGroup, loadingKey)}>
            提交
          </Button>
        </FormItem>
      </Form>
    );
  }
}

export default Form.create()(EditForm);
